package com.caifeng.redis.util.lock;

import com.caifeng.domain.ResponseCode;
import com.caifeng.domain.ServiceException;
import jakarta.annotation.Resource;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedissonLockUtil {

    @Resource
    private RedissonClient redissonClient;

    public void lock(String key) {

        RLock lock = redissonClient.getLock(key);
        try {
            if (!lock.tryLock(3L, 30L, TimeUnit.SECONDS)) {
                throw new ServiceException(ResponseCode.TRY_AGAIN);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        }
    }

    public void unLock(String key) {
        redissonClient.getLock(key).unlock();
    }
}
